package com.lefu.es.system;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lefu.es.constant.UtilConstants;
import com.lefu.es.entity.FitBitPostBo;
import com.lefu.es.entity.FitBitResponseBo;
import com.lefu.es.event.RevokeFitbit;
import com.lefu.es.util.FitbitHelper;
import com.lefu.es.util.MyUtil;
import com.lefu.es.util.OkManager;
import com.lefu.es.util.SharedPreferencesUtil;
import com.lefu.es.view.CircleProgressView;
import com.lefu.es.view.LoadingDialog;
import com.wellness.scale.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;

public class FitbitAuthActivity extends Activity {


    String url = "https://www.fitbit.com/oauth2/authorize?response_type=token&client_id=22CK9L&redirect_uri=http%3a%2f%2fwww.healthscale8.com%2fauth2%2findex.html&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight&expires_in=31536000";

    private LoadingDialog progressDialog = null;

    @Bind(R.id.back_textView)
    TextView back_textView;

    @Bind(R.id.title_textView)
    TextView title_textView;

    @Bind(R.id.web_view)
    WebView webView;

    @Bind(R.id.progress_ly)
    RelativeLayout progress_ly;

    @Bind(R.id.circle_progress)
    CircleProgressView mCircleProgressView;

    @Bind(R.id.sendBtn)
    Button button;

    private OkManager manager;

    private OkHttpClient clients;

    public static Intent creatIntent(Context context) {
        Intent intent = new Intent(context, FitbitAuthActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fitbit_auth);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        if (null == UtilConstants.su)
            UtilConstants.su = new SharedPreferencesUtil(FitbitAuthActivity.this);
        UtilConstants.FIBIT_USER_ID_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
        UtilConstants.FIBIT_ACCESS_TOKEN_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
        if (!TextUtils.isEmpty(UtilConstants.FIBIT_USER_ID_VALUE) && !TextUtils.isEmpty(UtilConstants.FIBIT_ACCESS_TOKEN_VALUE)) {
            UtilConstants.FIBIT_IS_OPEN = 1;
        } else {
            UtilConstants.FIBIT_IS_OPEN = 0;
        }
        initWebView();
        //manager = OkManager.getInstance();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RevokeFitbit postEvent) {
        boolean records = postEvent.isSuccess();
        if (records) {
            FitbitAuthActivity.this.finish();
        } else {
            //ToastUtils.ToastCenter(FitbitAuthActivity.this,getString(R.string.no_btn));
            FitbitAuthActivity.this.finish();
        }
    }

    ;

    private void showReAlertDailog(String title) {
        new com.lefu.es.view.AlertDialog(FitbitAuthActivity.this).builder()
                .setTitle(getResources().getString(R.string.waring_title))
                .setMsg(title)
                .setPositiveButton(getResources().getString(R.string.ok_btn), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FitbitHelper.getInstance().revokeToken();
                        // FitbitAuthActivity.this.finish();
                    }
                }).show();
    }


    @OnClick(R.id.sendBtn)
    void sendClick() {
        showReAlertDailog(getString(R.string.refitbit_auth) + "?");

        //Map<String, String> map = new HashMap<String, String>();
        //map.put("weight", "69.50");
        //map.put("date", "2017-11-03");
        //map.put("time", "14:30:10");
        // new DownloadTask().execute(map);
        //ToastUtils.ToastCenter(this,res);
    }

    public void showProgress() {

        progress_ly.setVisibility(View.VISIBLE);
        mCircleProgressView.spin();
    }

    public void hideProgress() {

        progress_ly.setVisibility(View.GONE);
        mCircleProgressView.stopSpinning();
    }

    class DownloadTask extends AsyncTask<Map<String, String>, Integer, String> {

        @Override
        protected String doInBackground(Map<String, String>... params) {
            UtilConstants.FIBIT_USER_ID_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, "");
            UtilConstants.FIBIT_ACCESS_TOKEN_VALUE = (String) UtilConstants.su.readbackUp("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, "");
            String url = FitbitHelper.getInstance().getPostWeightUrl(UtilConstants.FIBIT_USER_ID_VALUE);
            String res = manager.sentDataByPost(url, params[0], UtilConstants.FIBIT_ACCESS_TOKEN_VALUE);
            FitBitResponseBo rescords = JSON.parseObject(res, FitBitResponseBo.class);

            FitBitPostBo postBo = JSON.parseObject(rescords.getWeightLog(), FitBitPostBo.class);
            return res;
        }
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        // 得到设置属性的对象
        WebSettings webSettings = webView.getSettings();

        // 使能JavaScript
        webSettings.setJavaScriptEnabled(true);

        // 支持中文，否则页面中中文显示乱码
        webSettings.setDefaultTextEncodingName("GBK");

        // 限制在WebView中打开网页，而不用默认浏览器
        webView.setWebViewClient(new WebViewClient());

        // 清除缓存
        webView.clearCache(true);
        // 清除历史记录
        webView.clearHistory();
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
                Log.d("FitbitAuthActivity", "开始加载");
                showProgress();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                //complete();
                Log.d("FitbitAuthActivity", "加载结束");
                hideProgress();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http://www.healthscale8.com")) {
                    if (url.indexOf("#") > 0) {
                        String params = url.substring(url.indexOf("#") + 1);
                        String[] param = params.split("&");
                        Map<String, String> map = new HashMap();
                        for (String str : param) {
                            String[] par = str.split("=");
                            map.put(par[0].toLowerCase(), par[1]);
                        }
                        if (map.size() > 0) {
                            UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_ACCESS_TOKEN_KEY, map.get(UtilConstants.FIBIT_ACCESS_TOKEN));
                            UtilConstants.su.editSharedPreferences("lefuconfig", UtilConstants.FIBIT_USER_ID_KEY, map.get(UtilConstants.FIBIT_USER_ID));
                            UtilConstants.FIBIT_IS_OPEN = 1;
                            //授权成功
                            if ("zh".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/zh/fibit_open.html");
                            } else if ("en".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/en/fibit_open.html");
                            } else if ("fr".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/fr/fibit_open.html");
                            } else if ("es".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/es/fibit_open.html");
                            } else if ("de".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/de/fibit_open.html");
                            } else if ("it".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/it/fibit_open.html");
                            } else if ("ja".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                                webView.loadUrl("file:///android_asset/ja/fibit_open.html");
                            } else {
                                webView.loadUrl("file:///android_asset/en/fibit_open.html");
                            }

                            return true;

                        } else {
                            //授权失败
                            showAlertDailog(getResources().getString(R.string.fitbit_auth_failed));
                        }

                    } else {
                        //授权失败
                        showAlertDailog(getResources().getString(R.string.fitbit_auth_failed));
                    }
                    //back_textView.setText(url);
                }
                // load the webpage from url: login and grant access
                return super.shouldOverrideUrlLoading(view, url); // return false;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);

                if (newProgress == 100) {
                    Log.d("FitbitAuthActivity", "加载结束11111");
                    //complete();
                    progress_ly.setVisibility(View.GONE);
                } else {
                    Log.d("FitbitAuthActivity", "加载....");
                }
            }
        });
        if (UtilConstants.FIBIT_IS_OPEN == 0) {
            webView.loadUrl(url);
        } else {
            //授权成功
            if ("zh".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                webView.loadUrl("file:///android_asset/zh/fibit_open.html");
            } else if ("en".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                webView.loadUrl("file:///android_asset/en/fibit_open.html");
            } else if ("fr".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                webView.loadUrl("file:///android_asset/fr/fibit_open.html");
            } else if ("es".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                webView.loadUrl("file:///android_asset/es/fibit_open.html");
            } else if ("de".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                webView.loadUrl("file:///android_asset/de/fibit_open.html");
            } else if ("it".equals(MyUtil.getLanguage(FitbitAuthActivity.this))) {
                webView.loadUrl("file:///android_asset/it/fibit_open.html");
            } else {
                webView.loadUrl("file:///android_asset/en/fibit_open.html");
            }
        }

    }

    private void showAlertDailog(String title) {
        new com.lefu.es.view.AlertDialog(FitbitAuthActivity.this).builder()
                .setTitle(getResources().getString(R.string.waring_title))
                .setMsg(title)
                .setPositiveButton(getResources().getString(R.string.ok_btn), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();
    }


    @OnClick(R.id.back_textView)
    public void backClick() {
        FitbitAuthActivity.this.finish();
    }
}
